// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const users = db.collection('users')

// 云函数入口函数
exports.main = async (event, context) => {
  const { username, account, password, userType } = event
  
  try {
    // 检查手机号是否已注册
    const checkRes = await users.where({
      account
    }).count()
    
    if (checkRes.total > 0) {
      return {
        success: false,
        message: '该手机号已注册'
      }
    }
    
    // 创建新用户
    const createRes = await users.add({
      data: {
        username,
        account,
        password, // 注意：实际项目中密码应该加密存储
        userType,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      message: '注册成功',
      userId: createRes._id
    }
  } catch (err) {
    console.error('注册失败:', err)
    return {
      success: false,
      message: '注册失败，请稍后重试'
    }
  }
}